package com.soft.idc.common.service;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.soft.idc.common.model.IdcOrg;

public class IdcOrgService extends IdcOrg {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3856494413999469457L;
	
	public static List<Record> loadOrg() {
		String sql =  "SELECT O.ORG_ID, O.NAME, O.PARENT_ID FROM IDC_ORG O";
			List<Record> result = Db.find(sql);
			return result;
	}
	
	public static List<Record> loadParentOrg() {
		String sql =  "SELECT O.ORG_ID, O.NAME FROM IDC_ORG O WHERE O.PARENT_ID = -1";
			List<Record> result = Db.find(sql);
			return result;
	}
	
	/**
	 * 查询组织的子组织(包括其本身)
	 * @param orgId
	 * @return
	 */
	public static List<Record> querySubOrg(Integer orgId){
		//查询用户组织的所有子组织
		StringBuffer queryOrgSql = new StringBuffer();
		queryOrgSql.append("select o.org_id , o.name , o.parent_id from idc_org o where o.parent_id = ? or o.org_id = ?");
		queryOrgSql.append(" union ");
		queryOrgSql.append("select oo.org_id , oo.name , oo.parent_id from idc_org oo where oo.parent_id in ( ");
		queryOrgSql.append("select ooo.org_id from idc_org ooo where ooo.parent_id = ? ");
		queryOrgSql.append(") ");
		List<Record> orgList = Db.find(queryOrgSql.toString() , new Object[]{orgId, orgId, orgId});
		return orgList;		
	}
	
	public static String querySubOrgId(Integer orgId){
		List<Record> result = IdcOrgService.querySubOrg(orgId);
		StringBuffer orgIds = new StringBuffer();
		for(int i=0; i<result.size(); i++){
			if(i!=result.size()-1){
				orgIds.append(result.get(i).getInt("org_id") + ",");
			}else{
				orgIds.append(result.get(i).getInt("org_id"));
			}
		}
		return orgIds.toString();
	}
}
